//
//  SendMessageController.m
//  iengage
//
//  Created by Luis Ziliani on 3/6/09.
//  Copyright 2009 Manas. All rights reserved.
//

#import "SendMessageController.h"

#import "iengageAppDelegate.h"
#import "Util.h"

#define MaxCharacterPerMessage	140

@implementation SendMessageController

@synthesize navigationController, messageTextView, activityIndicatorView, sendButton, countProgressView, countLabel;


- (void) setCount: (int) count {
	if (count > MaxCharacterPerMessage) {
		[countLabel setText:[NSString stringWithFormat:@"%d chars over", count-MaxCharacterPerMessage]];
		[sendButton setEnabled:false];
	}
	else {
		[countLabel setText:[NSString stringWithFormat:@"%d chars left", MaxCharacterPerMessage-count]];
		[sendButton setEnabled:true];
	}
}

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


- (void)viewDidLoad {
    [super viewDidLoad];
	[messageTextView becomeFirstResponder];
	[self setCount:[[messageTextView text] length]];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (IBAction)sendMessage:(id)sender {
	NSString *msg = [messageTextView text];
	@try {
		IEngageAppDelegate * app = [[UIApplication sharedApplication] delegate];
				
		NSMutableString * url = [NSMutableString stringWithString:[app serverURL]];
		[url appendString:@"/sendMessage?"];
		[url appendFormat:@"msg=%@", [[msg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] 
									  stringByReplacingOccurrencesOfString:@"&" withString:@"%26"]];
		HttpRequestWithLogin *request = [[HttpRequestWithLogin alloc] init];
		[request openURL:url 
				withUser:[app currentUser] 
			 andPassword:[app userPassword] 
				delegate:self];
		
		[request autorelease];
		[activityIndicatorView startAnimating];
		[sendButton setEnabled:NO];
	}
	@catch (NSException * e) {
		[self informError:[e description]];
	}
}

/* 
 Each time the text changes, we show how much text is left
 */
- (void)textViewDidChange:(UITextView *)textView {
	int count = [[textView text] length];
	float progress = count / 140.0;
	if (progress > 1.0)
		progress = 1.0;
	
	[countProgressView setAlpha:(progress < 0.3? 0.3 : progress)];
	[countProgressView setProgress:progress];
	
	[self setCount:count];
}


- (void) informUnkownError {
	[self progressStop];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:   @"Could not send your message."  
												   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
	[alert show];
	[alert release];
}

- (void) informError: (NSString*) error {
	[self progressStop];
	NSString * msg = [[NSString alloc] initWithFormat:@"There has been an error during the process. Perhaps a bad configuration? The error is %@", error];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message: msg
												   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
	[alert show];
	[alert release];	
	[msg release];
}

- (void) showPreferencesCredentialsAreIncorrect {
	[self progressStop];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"User or password incorrect" message:   @"The user and password provided are incorrect. Please go to \"Settings -> iengage\" and check them."  
												   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
	[alert show];
	[alert release];
}

- (void) progressStop {
	[sendButton setEnabled:YES];
	[activityIndicatorView stopAnimating];
}

- (void) requestEndedOk {
	[self progressStop];
	[messageTextView setText:@""];
	[UIAlertView showWithTitle:@"Message sent" message:@"The message has been succesfully sent" dismissButton:@"OK"];
}



- (void)dealloc {
	[navigationController release];
	[messageTextView release];	
	[activityIndicatorView release];
	[sendButton release];
	[countProgressView release];
	[super dealloc];
}


@end
